package com.wisezone.studentmanager.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.wisezone.studentmanager.server.UserServer;
import com.wisezone.studentmanager.server.impl.UserServerImpl;
import com.wisezone.studentmanager.utils.WebContext;

@WebServlet({ "/RegisterServlet", "/register.servlet" })
public class RegisterServlet extends HttpServlet {
	// private static Logger logger = Logger.getLogger(RegisterServlet.class);
	private UserServer userServer = new UserServerImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		WebContext.foward("login/register", request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 创建一个文件上传解析器
		ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

		Map<String, String> paramterMap = new HashMap<>();
		try {
			List<FileItem> fileItems = servletFileUpload.parseRequest(request); // 解析表单
			for (FileItem fileItem : fileItems) {
				if (fileItem.isFormField() == true) { // 表单内容
					String name = fileItem.getFieldName(); // 表单属性名
					String value = fileItem.getString(); // 表单属性值

					paramterMap.put(name, value);

				} else { // 处理文件
					String name = fileItem.getFieldName(); // 表单属性名

					String path = request.getServletContext().getRealPath("/") + "upload/";
					System.out.println("path :" + path);
					String fname = getFileName(fileItem.getName());
					File saveFile = createFile(new File(path, fname));
					try {
						fileItem.write(saveFile);
					} catch (Exception e) {
						e.printStackTrace();
					}

					paramterMap.put(name, "upload/" + fname);
				}
			}

		} catch (FileUploadException e) {
			// logger.error(e.getMessage());
		}

		// 保存数据到数据库
		String message = userServer.register(paramterMap.get("username"), paramterMap.get("password"),
				paramterMap.get("myfile"));
		request.setAttribute("regsiterMsg", message);
		WebContext.foward("login/register", request, response);
	}

	/**
	 * 判断是否文件路径，如果是路径进行切割获取文件名 注:不同浏览器返回不一样，有些直接是文件名，有些是路径带文件名
	 * 
	 * @param filePath
	 *            E:\fun\picture1\item1.PNG; item2.png
	 * @return item1.PNG;item2.png
	 */
	public String getFileName(String filePath) {
		String fileName = filePath;
		if (filePath.contains("\\")) {
			int endIndex = filePath.lastIndexOf("\\");
			fileName = filePath.substring(endIndex + 1); // item1.PNG
		}
		return fileName;
	}

	/**
	 * 
	 * 创建多级文件目录 指定文件 如: e:/liu/hai/bing.txt
	 */
	public File createFile(File file) {
		if (file.exists()) {
			return file;
		}
		try {
			String fileDir = file.getPath();
			int lastIndex = fileDir.lastIndexOf(File.separator);
			String dir = fileDir.substring(0, lastIndex);
			File dirFile = new File(dir);
			dirFile.mkdirs();
			if (file.createNewFile()) {
				return file;
			} else {
				return null;
			}
		} catch (IOException e) {
			return null;
		}
	}

}
